/*
 * Copyright 2012 Andrea Parodi
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package eban.storebyrules.results;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;

/**
 * Author: parroit
 * Created: 07/05/12 9.47
 */
public class ResultsetAdapter implements Result {
    private final ResultSet resultSet;
    private final Statement stat;

    public ResultsetAdapter(ResultSet resultSet, Statement stat) {

        this.resultSet = resultSet;
        this.stat = stat;
    }
    private ResultSet result() {
        return this.resultSet;
    }

    @Override public Iterator<Row> iterator() {
        return new RowIterator(this);
    }

    private class ResultsetColumns implements Columns {

        @Override public Column[] all() {
            try {
                List<Column> buff= Lists.newArrayList();
                ResultSetMetaData metaData = result().getMetaData();
                for (int i=0;i< metaData.getColumnCount();i++){
                    buff.add(new DefaultColumn(i, metaData.getColumnName(i),ResultsetAdapter.this));
                }

                Column[] ret = new Column[buff.size()];
                return buff.toArray(ret);
            } catch (SQLException e) {
                throw new RuntimeException("cannot parse result columns",e);
            }
        }



        @Override public Column byName(String name) {
            try {
                return new DefaultColumn(result().findColumn(name), name,ResultsetAdapter.this);
            } catch (SQLException e) {
                throw new RuntimeException("cannot find given column.",e);
            }
        }

        @Override public Column at(int index) {
            try {
                ResultSetMetaData metaData = result().getMetaData();
                return new DefaultColumn(index, metaData.getColumnName(index),ResultsetAdapter.this);
            } catch (SQLException e) {
                throw new RuntimeException("cannot find given column.",e);
            }
        }

        @Override public int count() {
            try {
                ResultSetMetaData metaData = result().getMetaData();
                return metaData.getColumnCount();
            } catch (SQLException e) {
                throw new RuntimeException("cannot find given column.",e);
            }
        }
    }

    private class ResultsetRow implements Row {

        @Override public Object get(Column column) {
            Preconditions.checkNotNull(resultSet);
            try {
                return resultSet.getObject(column.getIndex());
            } catch (SQLException e) {
                throw new RuntimeException("cannot get value of cell for given column.",e);
            }
        }

        @Override public Result getResult() {
            return ResultsetAdapter.this;
        }
    }

    private final ResultsetRow currentRow = new ResultsetRow();
    private final ResultsetColumns columns = new ResultsetColumns();

    @Override public void next() {
        try {
            resultSet.next();
        } catch (SQLException e) {
            throw new RuntimeException("cannot move to next row.",e);
        }
    }

    @Override public Columns columns() {
        return columns;
    }

    @Override public Row current() {
        return atEnd() ? Rows.NO_CURRENT_ROW : currentRow;
    }

    @Override public boolean atEnd() {
        try {
            return resultSet.isAfterLast();
        } catch (SQLException e) {
            return true;
        }
    }

    @Override public void close() {
        try {
            stat.close();
            resultSet.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
